package com.sxhuayuan.parking.controller.admin;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.sxhuayuan.parking.controller.BaseController;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.Page;
import com.sxhuayuan.parking.compenent.Pageable;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.compenent.web.RespMessage.Status;
import com.sxhuayuan.parking.entity.Admin;
import com.sxhuayuan.parking.entity.BaseEntity;
import com.sxhuayuan.parking.exception.SessionTimeoutException;
import com.sxhuayuan.parking.service.AdminService;
import com.sxhuayuan.parking.service.RoleService;

@RestController("adminAdminController")
@RequestMapping("/admin/admin")
public class AdminController extends BaseController {

	// Logger log = LogManager.getLogger();
	Logger log = LoggerFactory.getLogger(getClass());

	@Resource(name = "adminServiceImpl")
	AdminService service;
	@Resource(name = "roleServiceImpl")
	RoleService roleService;

	@RequestMapping("/list")
	public RespMessage pagelist(@RequestBody Pageable pageable) {
		Page<Admin> page = service.findPage(pageable);
		return RespMessage.builder().success().setDatas(page).build();
	}

	/**
	 * 根据用户名和密码查询
	 */
	@RequestMapping("/getinfo")
	public RespMessage getCurrent() {
		Admin admin = service.getCurrent();
		if (admin == null) {
			throw new SessionTimeoutException();
		}
		JSONObject user = new JSONObject();
		user.put("name", admin.getName());
		user.put("username", admin.getUsername());
		user.put("avator", admin.getImgUrl());
		user.put("type", "admin");
		user.put("department", admin.getDepartment());
		List<String> auths = new ArrayList<>();
		admin.getRoles().forEach((v) -> auths.addAll(v.getAuthorities()));
		user.put("access", auths);
		return RespMessage.builder().success().setDatas(user).build();
	}

	/**
	 * 删除用户
	 */
	@RequestMapping("/delete")
	public RespMessage delete(Long id) {
		if (Objects.isNull(id)) {
			return RespMessage.error(Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		service.delete(id);
		return RespMessage.success();

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public RespMessage save(@Validated(BaseEntity.Save.class) @RequestBody Admin admin, HttpServletRequest request) {
		if (service.usernameExists(admin.getUsername())) {
			return RespMessage.builder().validError().setErr(Message.FORM_UNIQUE_INVALID, "用户名").build();
		}
		admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
		service.save(admin);
		return RespMessage.success();
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public RespMessage update(@Validated @RequestBody Admin admin) {
		Admin one = service.findOne(admin.getId());

		if (one == null) {
			return invalidToken();
		}

		String password = admin.getPassword();
		if (password != null && !"".equals(password)) {
			admin.setPassword(DigestUtils.md5Hex(password));
		} else {
			admin.setPassword(one.getPassword());
		}
		service.update(admin);
		return RespMessage.success();
	}

	@RequestMapping(value = "/get", method = RequestMethod.GET)
	public RespMessage get(Long id) {
		Admin admin = service.findOne(id);
		return RespMessage.builder().success().setDatas(admin).build();
	}

	/**
	 * 检查用户名是否存在
	 */
	@RequestMapping(value = "/check_username", method = RequestMethod.GET)
	public boolean checkUsername(String username) {
		if (StringUtils.isEmpty(username)) {
			return false;
		}
		return !service.usernameExists(username);
	}

	/**
	 * 锁定 启用
	 */
	@RequestMapping("/locked/or/enabled")
	public RespMessage onIsLockedAndEnabled(Long id, String type, Boolean value) {
		if (Objects.isNull(id) || !StringUtils.isNotBlank(type) || Objects.isNull(value)) {
			return RespMessage.error(Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		service.onIsLockedAndEnabled(id, type, value);
		return RespMessage.success();

	}

	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public RespMessage test() {
		for (int i = 0; i < 10; i++) {
			Admin admin = new Admin();
			admin.setUsername(RandomStringUtils.randomAlphabetic(6));
			admin.setPassword(RandomStringUtils.randomAlphabetic(6));
			admin.setName(RandomStringUtils.randomAlphabetic(6));
			admin.setLoginFailureCount(0);
			admin.setRoles(new HashSet<>(roleService.findList(1L)));
			service.save(admin);
		}
		return RespMessage.success();
	}

	@PostMapping("/changepassword")
	public RespMessage changePassword(@RequestParam String password, @RequestParam String updatePassword) {
		Admin current = service.getCurrent();
		if (current == null) {
			return invalidToken();
		}
		String s = DigestUtils.md5Hex(password);

		if (!s.equals(current.getPassword())) {
			return RespMessage.error("原密码输入错误");
		}

		String pattern = "^[^\\s&\"<>]+$";
		if (!(updatePassword.length() >= 4 && updatePassword.length() <= 64 && updatePassword.matches(pattern))) {
			return RespMessage.error("新密码格式不正确");
		}

		current.setPassword(DigestUtils.md5Hex(updatePassword));

		service.update(current);
		return RespMessage.success();
	}
}
